package com.example.controller;

import com.example.pojo.Result;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.utils.JwtUtils;
import com.example.utils.Md5Util;
import com.example.utils.ThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*") // 允许的前端源
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public Result register( String username, String password) {
        //查询用户
        User user = userService.findByUsername(username);
        if (user == null) {
            userService.register(username, password);
            //注册
            return Result.success("注册成功");
        } else {
            // 用户已存在
            return Result.error("用户名已存在");
        }
    }

    @PostMapping("/login")
    public Result login( String username, String password) {
        //根据用户名查询用户
        User user = userService.findByUsername(username);
        if(user == null){
            return Result.error("用户名不存在");
        }
        //判断密码是否正确
        if(Md5Util.getMD5String(password).equals(user.getPassword())){
            //成功
            Map<String, Object> Claims = new HashMap<>();
            Claims.put("id",user.getId());
            Claims.put("username",user.getUsername());
            String token = JwtUtils.generateJwt(Claims);//jwt包含了当前登录的用户信息
            return Result.success(token);
        }
        //查看用户账号状态，如果已经被禁用，则不让其登录
        if (user.getStatus() == 1){
            return Result.error("账号已被禁用");
        }

        return Result.error("账号或密码错误");
    }

//    用手机号登录
    @PostMapping("/loginByPhone")
    public Result loginByPhone( @RequestParam("phone") String phone, @RequestParam("code") String code) {
        //判断验证码是否正确(从Redis获取验证码并且校验)
        String token = userService.loginByPhone(phone, code);
        return Result.success(token);
    }

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    public Result sendCode(@RequestParam("phone") String phone) {
        // TODO 发送短信验证码并保存验证码
        return userService.sendCode(phone);
    }

    @GetMapping("/userInfo")
        public Result userInfo(/*@RequestHeader("token") String token*/) {
            //解析token
//            Claims claims = JwtUtils.parseJWT(token);
            Claims claims = ThreadLocalUtil.get();
            String username = (String) claims.get("username");
            User user = userService.findByUsername(username);
            return Result.success(user);
        }
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.update(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params){
        // 1.校验参数

        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("旧密码不正确");
        }
        if (!newPwd.equals(rePwd)){
            return Result.error("两次密码不一致");
        }
        userService.updatePwd(newPwd);
        return Result.success();
    }

    //查询用户列表（需要管理员权限）
    @GetMapping("/list")
    public Result list(){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        List<User> userList = userService.list();
        return Result.success(userList);
    }
    //禁用账号（管理员权限）
    @PatchMapping("/disable")
    public Result disable(@RequestParam("id") Integer id){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        userService.disable(id);
        return Result.success();
    }
    //删除账号（管理员权限）
    @DeleteMapping("/delete")
    public Result delete(@RequestParam("id") Integer id){
        Claims claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        User user = userService.findByUsername(username);
        if (user.getRole() != 3){
            return Result.error("权限不足");
        }
        userService.delete(id);
        return Result.success();
    }
    //检索用户（根据用户名或者id或者更多信息的条件查询）（管理员权限）
    @GetMapping("/search")
    public Result search(@RequestParam(required = false) String username,
                         @RequestParam(required = false) Integer id,
                         @RequestParam(required = false) String phone,
                         @RequestParam(required = false) Integer role){
        Claims claims = ThreadLocalUtil.get();
        Integer userid = (Integer) claims.get("id");
         User user = userService.findById(userid);
        if (user.getRole() != 3){
            return Result.error("需要管理员权限！");
        }
        List<User> userList = userService.search(username,id,phone,role);
        return Result.success(userList);
    }
    //根据id查询用户信息（不需要管理员权限）
    @GetMapping("/info")
    public Result info(@RequestParam("id") Integer id){
        User user = userService.findById(id);
        return Result.success(user);
    }


}
